package com.bigbird.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * 可以供多个客户端使用的网络程序
 */
public class BioServerV2 {
    public static void main(String[] args) throws IOException {
        try(ServerSocket socket = new ServerSocket()) {
            socket.bind(new InetSocketAddress(1881));
            while(true) {
                Socket accept = socket.accept();
                new Thread(()->{
                    InputStream inputStream;
                    try {
                        inputStream = accept.getInputStream();
                        accept.getOutputStream().write("hello world".getBytes(UTF_8));
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        String line;
                        while((line=bufferedReader.readLine())!=null){
                            System.out.println(line);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
            }
        }
    }

}
